#include "../../../common/etcd.hpp"
#include <gflags/gflags.h>
#include <brpc/server.h>
#include <butil/logging.h>
#include "main.pb.h"
#include <thread>

DEFINE_bool(run_mode, false, "程序的运行模式,0-调试,1-发布");
DEFINE_string(log_file, "", "发布模式下,用于指定日志的输出文件");
DEFINE_int32(log_level, 0, "发布模式下,用于指定日志的输出等级");

DEFINE_string(etcd_host, "http://127.0.0.1:2379", "服务注册中心地址");
DEFINE_string(base_service, "/service", "服务监控根目录");
DEFINE_string(echo_service, "/echo/instance", "当前实例名称");
DEFINE_string(access_host, "127.0.0.1:7070", "当前实例的外部访问地址");

DEFINE_int32(listen_port, 7070, "RPC服务监听端口");

class EchoServiceImpl : public example::EchoService
{
public:
    EchoServiceImpl() {}
    ~EchoServiceImpl() {}

    void Echo(google::protobuf::RpcController *controller,
              const ::example::EchoRequest *request,
              ::example::EchoResponse *response,
              ::google::protobuf::Closure *done)
    {
        brpc::ClosureGuard rpc_guard(done);
        std::cout << "收到消息: " << request->message() << std::endl;

        std::string resp = "服务器回应: " + request->message();
        response->set_message(resp);
        // 不使用brpc::ClosureGuard进行管理则由done调用Run()方法来表示完成响应
        // done->Run();
    }
};

int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc, &argv, true);
    hdp::init_logger(FLAGS_run_mode, FLAGS_log_file, FLAGS_log_level);

    // 关闭brpc的默认日志输出
    logging::LoggingSettings settings;
    settings.logging_dest = logging::LoggingDestination::LOG_TO_NONE;
    logging::InitLogging(settings);

    // 构造服务器对象
    brpc::Server server;
    // 向server中添加EchoService服务
    EchoServiceImpl echo_service;
    int ret = server.AddService(&echo_service, brpc::ServiceOwnership::SERVER_DOESNT_OWN_SERVICE);
    if (ret == -1)
    {
        std::cout << "添加RPC服务失败" << std::endl;
        return -1;
    }

    // 启动服务器
    brpc::ServerOptions options;
    // 连接空闲超时时间,超时后连接关闭
    options.idle_timeout_sec = -1;
    // IO线程数量
    options.num_threads = 1;

    ret = server.Start(FLAGS_listen_port, &options);
    if (ret == -1)
    {
        std::cout << "服务器启动失败" << std::endl;
        return -1;
    }

    // 注册服务
    // 注册时 /service/echo/instance ;  发现的时候 /service/echo
    hdp::Registry::ptr rclient = std::make_shared<hdp::Registry>(FLAGS_etcd_host);
    rclient->registry(FLAGS_base_service + FLAGS_echo_service, FLAGS_access_host);

    // 等待运行结束
    server.RunUntilAskedToQuit();
}